<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django-rest-framework框架/11-Book系列多表群操作 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django-rest-framework框架/11-Book系列多表群操作</h2>



  <p class="post-date">2020-07-12</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="Book系列连表接口"><a href="#Book系列连表接口" class="headerlink" title="Book系列连表接口"></a>Book系列连表接口</h1><h2 id="views-py"><a href="#views-py" class="headerlink" title="views.py"></a>views.py</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="comment"># Create your views here.</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> APIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ModelViewSet</span><br><span class="line"><span class="keyword">from</span> app01.models <span class="keyword">import</span> Book</span><br><span class="line"><span class="comment"># from app01.ser import BookSerializers</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.decorators <span class="keyword">import</span> action</span><br><span class="line"><span class="keyword">from</span> rest_framework.response <span class="keyword">import</span> Response</span><br><span class="line"><span class="keyword">from</span> rest_framework.authentication <span class="keyword">import</span> SessionAuthentication, BasicAuthentication</span><br><span class="line"><span class="comment"># class TestView(APIView):</span></span><br><span class="line"><span class="comment">#     def get(self,request):</span></span><br><span class="line"><span class="comment">#         1/0</span></span><br><span class="line"><span class="comment">#         return Response(&#123;'msg':'个人中心'&#125;)</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># class BookViewSet(ModelViewSet):</span></span><br><span class="line"><span class="comment">#     authentication_classes = [BasicAuthentication,]</span></span><br><span class="line"><span class="comment">#     queryset = Book.objects.all()</span></span><br><span class="line"><span class="comment">#     serializer_class = BookSerializers</span></span><br><span class="line">    <span class="comment"># @action(methods=['get'], detail=False)</span></span><br><span class="line">    <span class="comment"># def login(self, request):</span></span><br><span class="line">    <span class="comment">#     Book.objects.update_or_create()</span></span><br><span class="line">    <span class="comment">#     return Response(&#123;'msg':'登陆成功'&#125;)</span></span><br><span class="line">    <span class="comment"># @action(methods=['put'], detail=True)</span></span><br><span class="line">    <span class="comment"># def get_new_5(self, request,pk):</span></span><br><span class="line">    <span class="comment">#     return Response(&#123;'msg':'获取5条数据成功'&#125;)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> rest_framework.permissions <span class="keyword">import</span> AllowAny,IsAuthenticated,IsAdminUser,IsAuthenticatedOrReadOnly</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> app01.response <span class="keyword">import</span> APIResponse</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> ser <span class="keyword">as</span> serializers</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PublishAPIView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        pk = kwargs.get(<span class="string">'pk'</span>)</span><br><span class="line">        <span class="keyword">if</span> pk:</span><br><span class="line">            publish_obj = models.Publish.objects.filter(pk=pk).first()</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> publish_obj:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'pk error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line">            publish_data = serializers.PublishModelSerializer(publish_obj).data</span><br><span class="line">            <span class="keyword">return</span> APIResponse(results=publish_data)</span><br><span class="line"></span><br><span class="line">        publish_query = models.Publish.objects.all()</span><br><span class="line">        <span class="keyword">return</span> APIResponse(<span class="number">0</span>, <span class="string">'ok'</span>, data=serializers.PublishModelSerializer(publish_query, many=<span class="literal">True</span>).data)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookAPIView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="comment"># 单查、群查</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        pk = kwargs.get(<span class="string">'pk'</span>)</span><br><span class="line">        <span class="keyword">if</span> pk:</span><br><span class="line">            book_obj = models.Book.objects.filter(pk=pk, is_delete=<span class="literal">False</span>).first()</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> book_obj:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'pk error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line">            book_data = serializers.BookModelSerializer(book_obj).data</span><br><span class="line">            print(book_data)</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=book_data)</span><br><span class="line"></span><br><span class="line">        book_query = models.Book.objects.filter(is_delete=<span class="literal">False</span>).all()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> APIResponse(<span class="number">0</span>, <span class="string">'ok'</span>, data=serializers.BookModelSerializer(book_query, many=<span class="literal">True</span>).data)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 单删、群删</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">delete</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        单删：前台数据为pk，接口为 /books/(pk)/</span></span><br><span class="line"><span class="string">        群删：前台数据为pks，接口为 /books/</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        pk = kwargs.get(<span class="string">'pk'</span>)</span><br><span class="line">        <span class="comment"># 将单删群删逻辑整合</span></span><br><span class="line">        <span class="keyword">if</span> pk:  <span class="comment"># /books/(pk)/的接口就不考虑群删，就固定为单删</span></span><br><span class="line">            pks = [pk]</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            pks = request.data.get(<span class="string">'pks'</span>)</span><br><span class="line">        <span class="comment"># 前台数据有误(主要是群删没有提供pks)</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> pks:</span><br><span class="line">            <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'delete error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line">        <span class="comment"># 只要有操作受影响行，就是删除成功，反之失败</span></span><br><span class="line">        rows = models.Book.objects.filter(is_delete=<span class="literal">False</span>, pk__in=pks).update(is_delete=<span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">if</span> rows:</span><br><span class="line">            <span class="keyword">return</span> APIResponse(<span class="number">0</span>, <span class="string">'delete ok'</span>)</span><br><span class="line">        <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'delete failed'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 单增、群增</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        单增：前台提交字典，接口 /books/</span></span><br><span class="line"><span class="string">        群增：前台提交列表套字典，接口 /books/</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        request_data = request.data</span><br><span class="line">        <span class="keyword">if</span> isinstance(request_data, dict):  <span class="comment"># 单增</span></span><br><span class="line">            book_ser = serializers.BookModelSerializer(data=request_data)</span><br><span class="line">            <span class="keyword">if</span> book_ser.is_valid():</span><br><span class="line">                book_obj = book_ser.save()</span><br><span class="line">                <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj).data)</span><br><span class="line">            <span class="keyword">return</span> APIResponse(<span class="number">1</span>, msg=book_ser.errors)</span><br><span class="line">        <span class="keyword">elif</span> isinstance(request_data, list) <span class="keyword">and</span> len(request_data) != <span class="number">0</span> :  <span class="comment"># 群增</span></span><br><span class="line">            book_ser = serializers.BookModelSerializer(data=request_data, many=<span class="literal">True</span>)</span><br><span class="line">            book_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">            book_obj_list = book_ser.save()</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=<span class="literal">True</span>).data)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'data error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 单整体改、群整体改</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">put</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        单整体改：前台提交字典，接口 /books/(pk)/</span></span><br><span class="line"><span class="string">        群整体改：前台提交列表套字典，接口 /books/，注每一个字典都可以通过pk</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        pk = kwargs.get(<span class="string">'pk'</span>)</span><br><span class="line">        request_data = request.data</span><br><span class="line">        <span class="keyword">if</span> pk: <span class="comment"># 单改</span></span><br><span class="line">            <span class="keyword">try</span>:</span><br><span class="line">                book_obj = models.Book.objects.get(pk=pk)</span><br><span class="line">            <span class="keyword">except</span>:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'pk error'</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 修改和新增，都需要通过数据，数据依旧给data，修改与新增不同点，instance要被赋值为被修改对象</span></span><br><span class="line">            book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data)</span><br><span class="line">            book_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">            book_obj = book_ser.save()</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj).data)</span><br><span class="line">        <span class="keyword">else</span>:  <span class="comment"># 群改</span></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> isinstance(request_data, list) <span class="keyword">or</span> len(request_data) == <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'data error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment"># [&#123;pk:1,...&#125;, &#123;pk:3,...&#125;, &#123;pk:100,...&#125;] =&gt; [obj1, obj3, obj100] + [&#123;...&#125;, &#123;...&#125;, &#123;...&#125;]</span></span><br><span class="line">            <span class="comment"># 要考虑pk对应的对象是否被删，以及pk没有对应的对象</span></span><br><span class="line">            <span class="comment"># 假设pk3被删，pk100没有 =&gt; [obj1] + [&#123;...&#125;]</span></span><br><span class="line"></span><br><span class="line">            <span class="comment"># 注：一定不要在循环体中对循环对象进行增删(影响对象长度)的操作</span></span><br><span class="line">            obj_list = []</span><br><span class="line">            data_list = []</span><br><span class="line">            <span class="keyword">for</span> dic <span class="keyword">in</span> request_data:</span><br><span class="line">                <span class="comment"># request_data可能是list，单内部不一定是dict</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    pk = dic.pop(<span class="string">'pk'</span>)</span><br><span class="line">                    <span class="keyword">try</span>:</span><br><span class="line">                        obj = models.Book.objects.get(pk=pk, is_delete=<span class="literal">False</span>)</span><br><span class="line">                        obj_list.append(obj)</span><br><span class="line">                        data_list.append(dic)</span><br><span class="line">                    <span class="keyword">except</span>:</span><br><span class="line">                        <span class="keyword">pass</span></span><br><span class="line">                <span class="keyword">except</span>:</span><br><span class="line">                    <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'data error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line"></span><br><span class="line">            book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=<span class="literal">True</span>)</span><br><span class="line">            book_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">            book_obj_list = book_ser.save()</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=<span class="literal">True</span>).data)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 单局部改、群局部改</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">patch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        单整体改：前台提交字典，接口 /books/(pk)/</span></span><br><span class="line"><span class="string">        群整体改：前台提交列表套字典，接口 /books/，注每一个字典都可以通过pk</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        pk = kwargs.get(<span class="string">'pk'</span>)</span><br><span class="line">        request_data = request.data</span><br><span class="line">        <span class="keyword">if</span> pk:</span><br><span class="line">            <span class="keyword">try</span>:</span><br><span class="line">                book_obj = models.Book.objects.get(pk=pk)</span><br><span class="line">            <span class="keyword">except</span>:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'pk error'</span>)</span><br><span class="line">            <span class="comment"># 局部修改就是在整体修改基础上设置partial=True，将所有参与反序列化字段设置为required=False</span></span><br><span class="line">            book_ser = serializers.BookModelSerializer(instance=book_obj, data=request_data, partial=<span class="literal">True</span>)</span><br><span class="line">            book_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">            book_obj = book_ser.save()</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj).data)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:  <span class="comment"># 群改</span></span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> isinstance(request_data, list) <span class="keyword">or</span> len(request_data) == <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'data error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line"></span><br><span class="line">            <span class="comment"># [&#123;pk:1,...&#125;, &#123;pk:3,...&#125;, &#123;pk:100,...&#125;] =&gt; [obj1, obj3, obj100] + [&#123;...&#125;, &#123;...&#125;, &#123;...&#125;]</span></span><br><span class="line">            <span class="comment"># 要考虑pk对应的对象是否被删，以及pk没有对应的对象</span></span><br><span class="line">            <span class="comment"># 假设pk3被删，pk100没有 =&gt; [obj1] + [&#123;...&#125;]</span></span><br><span class="line"></span><br><span class="line">            <span class="comment"># 注：一定不要在循环体中对循环对象进行增删(影响对象长度)的操作</span></span><br><span class="line">            obj_list = []</span><br><span class="line">            data_list = []</span><br><span class="line">            <span class="keyword">for</span> dic <span class="keyword">in</span> request_data:</span><br><span class="line">                <span class="comment"># request_data可能是list，单内部不一定是dict</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    pk = dic.pop(<span class="string">'pk'</span>)</span><br><span class="line">                    <span class="keyword">try</span>:</span><br><span class="line">                        obj = models.Book.objects.get(pk=pk, is_delete=<span class="literal">False</span>)</span><br><span class="line">                        obj_list.append(obj)</span><br><span class="line">                        data_list.append(dic)</span><br><span class="line">                    <span class="keyword">except</span>:</span><br><span class="line">                        <span class="keyword">pass</span></span><br><span class="line">                <span class="keyword">except</span>:</span><br><span class="line">                    <span class="keyword">return</span> APIResponse(<span class="number">1</span>, <span class="string">'data error'</span>, http_status=<span class="number">400</span>)</span><br><span class="line"></span><br><span class="line">            book_ser = serializers.BookModelSerializer(instance=obj_list, data=data_list, many=<span class="literal">True</span>, partial=<span class="literal">True</span>)</span><br><span class="line">            book_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">            book_obj_list = book_ser.save()</span><br><span class="line">            <span class="keyword">return</span> APIResponse(data=serializers.BookModelSerializer(book_obj_list, many=<span class="literal">True</span>).data)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorAPIView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        authors=models.Author.objects.all()</span><br><span class="line">        author_ser=serializers.AuthorModelSerializer(authors,many=<span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">return</span> APIResponse(data=author_ser.data)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">put</span><span class="params">(self,reuqest,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        author_ser=serializers.AuthorModelSerializer(data=request.data)</span><br><span class="line">        author_ser.is_valid(raise_exception=<span class="literal">True</span>)</span><br><span class="line">        author_ser.save()</span><br><span class="line">        <span class="keyword">return</span> APIResponse()</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">delete</span><span class="params">(self,request,*args,**kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<h2 id="ser-py"><a href="#ser-py" class="headerlink" title="ser.py"></a>ser.py</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> rest_framework <span class="keyword">import</span> serializers</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookListSerializer</span><span class="params">(serializers.ListSerializer)</span>:</span></span><br><span class="line">    <span class="comment"># 1、create方法父级ListSerializer已经提供了</span></span><br><span class="line">    <span class="comment"># def create(self, validated_data):</span></span><br><span class="line">    <span class="comment">#     # 通过self.child来访问绑定的ModelSerializer</span></span><br><span class="line">    <span class="comment">#     print(self.child)</span></span><br><span class="line">    <span class="comment">#     raise Exception('我不提供')</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 2、父级ListSerializer没有通过update方法的实现体，需要自己重写</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">update</span><span class="params">(self, instance, validated_data)</span>:</span></span><br><span class="line">        <span class="comment"># print(instance)</span></span><br><span class="line">        <span class="comment"># print(validated_data)</span></span><br><span class="line">        <span class="keyword">return</span> [</span><br><span class="line">            self.child.update(instance[i], attrs) <span class="keyword">for</span> i, attrs <span class="keyword">in</span> enumerate(validated_data)</span><br><span class="line">        ]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookModelSerializer</span><span class="params">(serializers.ModelSerializer)</span>:</span></span><br><span class="line">    <span class="comment"># 通过BookModelSerializer.Meta.list_serializer_class来访问绑定的ListSerializer</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        <span class="comment"># 关联ListSerializer完成群增群改</span></span><br><span class="line">        list_serializer_class = BookListSerializer</span><br><span class="line"></span><br><span class="line">        model = models.Book</span><br><span class="line">        <span class="comment"># fields = ('name', 'price', 'publish', 'authors')</span></span><br><span class="line">        <span class="comment"># fields = ('name', 'price', 'publish_name', 'author_list')</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 了解</span></span><br><span class="line">        <span class="comment"># fields = '__all__'</span></span><br><span class="line">        <span class="comment"># exclude = ('id', )</span></span><br><span class="line">        <span class="comment"># depth = 1</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 序列化与反序列化整合</span></span><br><span class="line">        fields = (<span class="string">'name'</span>, <span class="string">'price'</span>, <span class="string">'publish_name'</span>, <span class="string">'author_list'</span>, <span class="string">'publish'</span>, <span class="string">'authors'</span>)</span><br><span class="line">        extra_kwargs = &#123;</span><br><span class="line">            <span class="string">'publish'</span>: &#123;</span><br><span class="line">                <span class="string">'write_only'</span>: <span class="literal">True</span></span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="string">'authors'</span>: &#123;</span><br><span class="line">                <span class="string">'write_only'</span>: <span class="literal">True</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 前提：如果只有查需求的接口，自定义深度还可以用子序列化方式完成</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PublishModelSerializer</span><span class="params">(serializers.ModelSerializer)</span>:</span></span><br><span class="line">    <span class="comment"># 子序列化都是提供给外键(正向方向)完成深度查询的，外键数据是唯一：many=False；不唯一：many=True</span></span><br><span class="line">    <span class="comment"># 注：只能参与序列化，且反序列化不能写(反序列化外键字段会抛异常)</span></span><br><span class="line">    books = BookModelSerializer(many=<span class="literal">True</span>)</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        model = models.Publish</span><br><span class="line">        fields = (<span class="string">'name'</span>, <span class="string">'address'</span>, <span class="string">'books'</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorModelSerializer</span><span class="params">(serializers.ModelSerializer)</span>:</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        model=models.Author</span><br><span class="line">        fields=(<span class="string">'name'</span>,<span class="string">'sex'</span>,<span class="string">'mobile'</span>,<span class="string">'mobile_in'</span>)</span><br><span class="line">        extra_kwargs=&#123;</span><br><span class="line">            <span class="string">'mobile'</span>:&#123;</span><br><span class="line">                <span class="string">'read_only'</span>: <span class="literal">True</span></span><br><span class="line">            &#125;,</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    mobile_in=serializers.CharField(write_only=<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># def validate_mobile_in(self, data):</span></span><br><span class="line">    <span class="comment">#     print(data)</span></span><br><span class="line">    <span class="comment">#     return data</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create</span><span class="params">(self, validated_data)</span>:</span></span><br><span class="line">        print(validated_data)</span><br><span class="line">        mobile=validated_data.pop(<span class="string">'mobile_in'</span>)</span><br><span class="line">        author=models.Author.objects.create(**validated_data)</span><br><span class="line">        authordetail=models.AuthorDetail.objects.create(mobile=mobile,author=author)</span><br><span class="line">        <span class="keyword">return</span> author</span><br></pre></td></tr></table></figure>

<h2 id="models-py"><a href="#models-py" class="headerlink" title="models.py"></a>models.py</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 一、基表</span></span><br><span class="line"><span class="comment"># Model类的内部配置Meta类要设置abstract=True，这样的Model类就是用来作为基表</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 多表：Book，Publish，Author，AuthorDetail</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseModel</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    is_delete = models.BooleanField(default=<span class="literal">False</span>)</span><br><span class="line">    create_time = models.DateTimeField(auto_now_add=<span class="literal">True</span>)</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        <span class="comment"># 基表必须设置abstract，基表就是给普通Model类继承使用的，设置了abstract就不会完成数据库迁移完成建表</span></span><br><span class="line">        abstract = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(BaseModel)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">    price = models.DecimalField(max_digits=<span class="number">5</span>, decimal_places=<span class="number">2</span>)</span><br><span class="line">    publish = models.ForeignKey(to=<span class="string">'Publish'</span>, related_name=<span class="string">'books'</span>, db_constraint=<span class="literal">False</span>, on_delete=models.DO_NOTHING)</span><br><span class="line">    <span class="comment"># 重点：多对多外键实际在关系表中，ORM默认关系表中两个外键都是级联</span></span><br><span class="line">    <span class="comment"># ManyToManyField字段不提供设置on_delete，如果想设置关系表级联，只能手动定义关系表</span></span><br><span class="line">    authors = models.ManyToManyField(to=<span class="string">'Author'</span>, related_name=<span class="string">'books'</span>, db_constraint=<span class="literal">False</span>)</span><br><span class="line">		</span><br><span class="line">    <span class="comment"># 自定义连表深度，不需要反序列化，因为自定义插拔属性不参与反序列化</span></span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">publish_name</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.publish.name</span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">author_list</span><span class="params">(self)</span>:</span></span><br><span class="line">        temp_author_list = []</span><br><span class="line">        <span class="keyword">for</span> author <span class="keyword">in</span> self.authors.all():</span><br><span class="line">            temp_author_list.append(&#123;</span><br><span class="line">                <span class="string">'name'</span>: author.name,</span><br><span class="line">                <span class="string">'sex'</span>: author.get_sex_display(),</span><br><span class="line">                <span class="string">'mobile'</span>: author.detail.mobile</span><br><span class="line">            &#125;)</span><br><span class="line">        <span class="keyword">return</span> temp_author_list</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Publish</span><span class="params">(BaseModel)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">    address = models.CharField(max_length=<span class="number">64</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(BaseModel)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">    sex = models.IntegerField(choices=[(<span class="number">0</span>, <span class="string">'男'</span>),(<span class="number">1</span>, <span class="string">'女'</span>)], default=<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AuthorDetail</span><span class="params">(BaseModel)</span>:</span></span><br><span class="line">    mobile = models.CharField(max_length=<span class="number">11</span>)</span><br><span class="line">    <span class="comment"># 有作者可以没有详情，删除作者，详情一定会被级联删除</span></span><br><span class="line">    <span class="comment"># 外键字段为正向查询字段，related_name是反向查询字段</span></span><br><span class="line">    author = models.OneToOneField(to=<span class="string">'Author'</span>, related_name=<span class="string">'detail'</span>, db_constraint=<span class="literal">False</span>, on_delete=models.CASCADE)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 二、表断关联</span></span><br><span class="line"><span class="comment"># 1、表之间没有外键关联，但是有外键逻辑关联(有充当外键的字段)</span></span><br><span class="line"><span class="comment"># 2、断关联后不会影响数据库查询效率，但是会极大提高数据库增删改效率（不影响增删改查操作）</span></span><br><span class="line"><span class="comment"># 3、断关联一定要通过逻辑保证表之间数据的安全</span></span><br><span class="line"><span class="comment"># 4、断关联</span></span><br><span class="line"><span class="comment"># 5、级联关系</span></span><br><span class="line"><span class="comment">#       作者没了，详情也没：on_delete=models.CASCADE</span></span><br><span class="line"><span class="comment">#       出版社没了，书还是那个出版社出版：on_delete=models.DO_NOTHING</span></span><br><span class="line"><span class="comment">#       部门没了，员工没有部门(空不能)：null=True, on_delete=models.SET_NULL</span></span><br><span class="line"><span class="comment">#       部门没了，员工进入默认部门(默认值)：default=0, on_delete=models.SET_DEFAULT</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 三、ORM外键设计</span></span><br><span class="line"><span class="comment"># 1、一对多：外键放在多的一方</span></span><br><span class="line"><span class="comment"># 2、多对多：外键放在常用的一方</span></span><br><span class="line"><span class="comment"># 3、一对一：外键放在不常用的一方</span></span><br><span class="line"><span class="comment"># 4、外键字段为正向查询字段，related_name是反向查询字段</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># from django.contrib.auth.models import AbstractUser, User</span></span><br><span class="line"><span class="comment"># class MyUser(AbstractUser):</span></span><br><span class="line"><span class="comment">#     pass</span></span><br></pre></td></tr></table></figure>

<h2 id="setting-py"><a href="#setting-py" class="headerlink" title="setting.py"></a>setting.py</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">LANGUAGE_CODE = <span class="string">'zh-hans'</span></span><br><span class="line"></span><br><span class="line">TIME_ZONE = <span class="string">'Asia/shanghai'</span></span><br><span class="line"></span><br><span class="line">USE_I18N = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">USE_L10N = <span class="literal">True</span></span><br><span class="line"></span><br><span class="line">USE_TZ = <span class="literal">False</span></span><br></pre></td></tr></table></figure>

<h2 id="urls-py"><a href="#urls-py" class="headerlink" title="urls.py"></a>urls.py</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">path(<span class="string">r'publishes/'</span>, views.PublishAPIView.as_view()),</span><br><span class="line">re_path(<span class="string">r'^publishes/(?P&lt;pk&gt;\d+)/$'</span>, views.PublishAPIView.as_view()),</span><br><span class="line"></span><br><span class="line">path(<span class="string">r'books/'</span>, views.BookAPIView.as_view()),</span><br><span class="line">re_path(<span class="string">r'^books/(?P&lt;pk&gt;\d+)/$'</span>, views.BookAPIView.as_view()),</span><br></pre></td></tr></table></figure>

</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/linux/%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/17-Linux%E8%AE%A1%E5%88%92%E4%BB%BB%E5%8A%A1/">
        <span class="nav-arrow">← </span>
        
          linux/入门到精通/17-Linux计划任务
        
      </a>
    
    
      <a class="nav-right" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/12-RBAC-%E5%9F%BA%E4%BA%8E%E8%A7%92%E8%89%B2%E7%9A%84%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6/">
        
          python/Django-rest-framework框架/12-RBAC-基于角色的访问控制
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#Book系列连表接口"><span class="toc-nav-text">Book系列连表接口</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#views-py"><span class="toc-nav-text">views.py</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#ser-py"><span class="toc-nav-text">ser.py</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#models-py"><span class="toc-nav-text">models.py</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#setting-py"><span class="toc-nav-text">setting.py</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#urls-py"><span class="toc-nav-text">urls.py</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django-rest-framework框架/11-Book系列多表群操作/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django-rest-framework框架/11-Book系列多表群操作",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>